<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\Article;
use App\Admin\Repositories\ArticleCategory;
use App\Models\SystemRegion;
use Dcat\Admin\Admin;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Controllers\AdminController;
use Dcat\Admin\Support\Helper;

class ArticleController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    public static function grid($categoryId = 0)
    {
        return Grid::make(new Article(), function (Grid $grid) use ($categoryId) {
            // 从其他模块过来的，只能管理该模块下的文章
            if ($categoryId) {
                // 模块管理员仅可查看公共分类和自己所属地区所在的文章
                $region_id = Admin::user()->region_id;
                if ($region_id > 0) {
                    $grid->model()->whereIn('region_id', [0, $region_id]);
                }

                $grid->model()->whereIn('category_id', ArticleCategory::getChild($categoryId));
                $grid->model()->orderBy('is_top', 'desc')->orderBy('weight', 'desc')->orderBy('id', 'desc');
            }
            $grid->column('id')->sortable();
            $grid->column('article_title');
            $grid->column('types', '类型')->display(function ($types) {
                // 文章类型（1图文，2视频，3短视频）
                return $types == 1 ? '图文' : ($types == 2 ? '视频' : ($types == 3 ? '短视频' : '音频'));
            });
            $grid->column('list_img')->image('', 60, 60);
            $grid->column('category_id', '分类')->display(function ($category_id) {
                if ($category_id) {
                    $ategory = \App\Models\ArticleCategory::find($category_id);
                    return $ategory ? $ategory->category_name : '';
                } else {
                    return '';
                }
            });
            $grid->column('is_top')->switch()->sortable();
            $grid->column('is_show', '展示')->switch()->sortable();
            $grid->column('weight')->sortable();
//            $grid->column('imgs');
//            $grid->column('video_url');
//            $grid->column('region_id');
//            $grid->column('read_num');
//            $grid->column('zan_num');
//            $grid->column('collect_num');
//            $grid->column('like_num');
//            $grid->column('share_num');
//            $grid->column('user_id');
//            $grid->column('admin_id');
//            $grid->column('is_admin');
//            $grid->column('types');
//            $grid->column('updated_at')->sortable();
            $grid->column('created_at');

            $grid->disableViewButton(); // 禁用详情按钮
            $grid->quickSearch(['article_title', 'content'])->placeholder('搜索...');

            $region_id = Admin::user()->region_id;
            $category = ArticleCategory::getList($categoryId, 3, 0, 0, $region_id);
            if ($category) {
                $grid->selector(function (Grid\Tools\Selector $selector) use ($category) {
                    $selector->selectOne('category_id', '分类筛选', $category);
                });
            }

        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    public static function detail($id)
    {
        return Show::make($id, new Article(), function (Show $show) {
            $show->field('id');
            $show->field('article_title');
            $show->field('content');
            $show->field('list_img');
            $show->field('imgs');
            $show->field('video_url');
            $show->field('region_id');
            $show->field('read_num');
            $show->field('zan_num');
            $show->field('collect_num');
            $show->field('like_num');
            $show->field('share_num');
            $show->field('category_id');
            $show->field('is_top');
            $show->field('weight');
            $show->field('user_id');
            $show->field('admin_id');
            $show->field('is_admin');
            $show->field('types');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    public static function form($categoryId = 0)
    {
        return Form::make(new Article(), function (Form $form) use ($categoryId) {
            $form->display('id');
            $form->text('article_title')->required();

            $region_id = Admin::user()->region_id;
            $category = \App\Admin\Repositories\ArticleCategory::getList($categoryId, 3, $categoryId ? 0 : 1, $categoryId, $region_id);
            $needRegionCategory = \App\Admin\Repositories\ArticleCategory::needRegionIDCategory();
            $form->select('category_id', '所属分类')
                ->when($needRegionCategory, function (Form $form) {
                    $region_id = Admin::user()->region_id;
                    if ($region_id) {
                        // 非总管理员
                        $region = SystemRegion::find($region_id);
                        $form->select('region_id', '所属地区')->options([$region_id => $region->region_name])->default($region_id, true);
                    } else {
                        $region = \App\Admin\Repositories\SystemRegion::getList();
                        $form->select('region_id', '所属地区')->options($region)->default(0, true);
                    }
                })
                ->options($category)
                ->required()
                ->default(0, true);

            $form->image('list_img')->move('article/'.date('Y-m-d'))->autoUpload()->help('短视频类型内容若未上传列表图片系统将会自动生成列表截图');

            // 文章类型（1图文，2视频，3短视频）
//            $typeOptions = [1 => '图文', 2 => '视频', 3 => '短视频'];
            $typeOptions = [1 => '图文', 3 => '短视频',4=>'音频'];
            $form->radio('types')
                ->when([1], function (Form $form) {
                    $form->multipleImage('imgs')->move('article/'.date('Y-m-d'))->saving(function ($paths) {
                        $paths = Helper::array($paths);
                        return json_encode($paths, true); // 最终转化为json保存到数据库
                    })->customFormat(function ($paths) {
                        return Helper::array($paths); // 转为数组
                    })->autoUpload();

                    $form->editor('content');
                })
                ->when(2, function (Form $form) {
                    $form->file('video_url', '视频')->move('video/'.date('Y-m-d'))->maxSize(1024 * 50)->accept('mp4')->autoUpload()->help('视频文件要求mp4格式且不超过50M');
                })
                ->when(3, function (Form $form) {
                    $form->file('video_url', '短视频')->move('video/'.date('Y-m-d'))->disableChunked()->maxSize(1024 * 50)->accept('mp4')->autoUpload()->help('视频文件要求mp4格式且不超过50M');
				  //$form->file('video_url', '短视频')->disableChunked()->autoUpload()->maxSize(1024 * 100)->accept('mp4')->url('upload/upload_video')->help('视频文件要求mp4格式且不超过100M');
                })
				->when([4], function (Form $form) {
					
                    $form->file('mp3_url', '音频')->move('mp3/'.date('Y-m-d'))->disableChunked()->maxSize(1024 * 50)->accept('mp3')->autoUpload()->help('语音文件要求mp3格式且不超过50M');
					$form->editor('content1');
                })
                ->options($typeOptions)
                ->required()
                ->default(1);

            $form->radio('is_top', '置顶')->options([1 => '是', 0 => '否'])->default(0);
            $form->radio('is_show', '展示')->options([1 => '是', 0 => '否'])->default(1);
            $form->number('weight')->placeholder('权重越高文章越靠前');

            $form->number('read_num');
            $form->number('zan_num');
            $form->number('collect_num');
            $form->number('like_num');
            $form->number('share_num');
            $form->hidden('admin_id')->value(Admin::user()->getKey());
            $form->hidden('is_admin')->value(1);
            $form->display('created_at');
            $form->display('updated_at');
            $form->disableViewCheck(true);

            // 表单提交前调用
            $form->submitted(function ($form) {
                // 短视频截图
                if ($form->types == 3 && !$form->list_img && $form->video_url) {
                    $stream_path = public_path('/uploads/'.$form->video_url);
                    $video_cover_name = 'video/'.get_file_name($stream_path).'.jpg';
                    $form->list_img = get_video_cover($stream_path, $video_cover_name);
                }
                if (!$form->region_id) {
                    $form->region_id = 0;
                }
            });
        });
    }
}
